import axios from 'axios';
import Cookies from 'vue-cookies';
// import Cookies from 'js-cookie';
import { Message } from 'element-ui';

var service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    timeout: 50000,
    headers: { 'content-type': 'application/json;charset=utf-8' },
});

service.interceptors.request.use(
    (config) => {
        let token = Cookies.get('ydcx_Yahv.Erp');
        if (token) {
            config.headers['Authorization'] = 'Bearer ' + token;
        }
        return config;
    },
    (err) => {
        Message({
            showClose: true,
            message: '请求超时...',
            type: 'error',
        });
        return Promise.reject(err);
    }
);
let resFlag = 0;
service.interceptors.response.use(
    (response) => {
        resFlag = 0;
        if (response.data.token) {
            //测试 使用
            Cookies.set('ydcx_Yahv.Erp', response.data.token);
        }
        const data = response.data;
        if (response.status == 200) {
            return data;
        } else {
            return { data: null, msg: '请求出错' };
        }
    },
    //接口错误状态处理，也就是说无响应时的处理
    (error) => {
        if (error && error.response) {
            resFlag++;
            switch (error.response.status) {
                case 400:
                    error.message = '请求错误(400)';
                    break;
                case 401:
                    error.message = '未授权，请重新登录(401)';
                    window.location.reload();
                    break;
                case 403:
                    error.message = '拒绝访问(403)';
                    break;
                case 404:
                    error.message = '请求出错(404)';
                    break;
                case 408:
                    error.message = '请求超时(408)';
                    break;
                case 500:
                    error.message = '服务器错误(500)';
                    break;
                case 501:
                    error.message = '服务未实现(501)';
                    break;
                case 502:
                    error.message = '网络错误(502)';
                    break;
                case 503:
                    error.message = '服务不可用(503)';
                    break;
                case 504:
                    error.message = '网络超时(504)';
                    break;
                case 505:
                    error.message = 'HTTP版本不受支持(505)';
                    break;
                default:
                    error.message = `连接出错(${error.response.status})!`;
            }
        } else {
            error.message = '连接服务器失败!';
        }
        if (resFlag == 1) {
            Message({
                showClose: true,
                message: error.message,
                type: 'error',
            });
        }
        return Promise.resolve(error);
    }
);

export { service };